
#include <base.hpp>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>

int main() {
    // 1. 创建 TCP 套接字
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        perror("socket failed");
        return -1;
    }

    // 2. 设置地址复用（否则 TIME_WAIT 状态下无法快速重启）
    int opt = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    // 3. 绑定本地 IP 和端口
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;           // IPv4
    addr.sin_port = htons(8080);         // 端口号（主机字节序→网络字节序）
    addr.sin_addr.s_addr = INADDR_ANY;   // 绑定到所有本地 IP（0.0.0.0）

    if (bind(server_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind failed");
        close(server_fd);
        return -1;
    }

    printf("Bind success on port 8080\n");

    // 4. 开始监听（TCP）
    listen(server_fd, 5);

    //接收字符串输出
    while (true) {
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_addr_len);
        if (client_fd < 0) {
            perror("accept failed");
            continue;
        }

        char buffer[1024];
        ssize_t bytes_received = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
        if (bytes_received < 0) {
            perror("recv failed");
            close(client_fd);
            continue;
        }

        buffer[bytes_received] = '\0'; // Null-terminate the received string
        printf("Received: %s\n", buffer);
        //响应数据
        const char* response = "Message received\n";
        send(client_fd, response, strlen(response), 0);
        

        close(client_fd);
    }
        
    return 0;
}